<template>
  <div class="animate-fadeIn">
    <div class="mb-6">
      <h2 class="text-2xl font-bold cyber-text mb-2">任务管理</h2>
      <p class="text-gray-400">查看和管理所有测试任务</p>
    </div>
    
    <div class="glass-effect rounded-xl p-6 tech-card">
      <div class="flex justify-between items-center mb-6">
        <div class="flex items-center space-x-4">
          <input 
            v-model="searchQuery"
            type="text" 
            placeholder="搜索任务..." 
            class="px-4 py-2 bg-gray-800/50 border border-gray-600 rounded-lg text-white focus:ring-2 focus:ring-tech-blue"
          >
          <select 
            v-model="statusFilter"
            class="px-4 py-2 bg-gray-800/50 border border-gray-600 rounded-lg text-white"
          >
            <option value="">全部状态</option>
            <option value="running">运行中</option>
            <option value="completed">已完成</option>
            <option value="failed">失败</option>
            <option value="pending">等待中</option>
          </select>
        </div>
        <router-link 
          to="/task/create"
          class="cyber-button px-4 py-2 text-white rounded-lg"
        >
          <i class="fas fa-plus mr-2"></i>新建任务
        </router-link>
      </div>
      
      <div class="overflow-x-auto">
        <table class="w-full">
          <thead>
            <tr class="border-b border-gray-700">
              <th class="text-left py-4 px-4 text-gray-300 font-medium">任务ID</th>
              <th class="text-left py-4 px-4 text-gray-300 font-medium">任务名称</th>
              <th class="text-left py-4 px-4 text-gray-300 font-medium">状态</th>
              <th class="text-left py-4 px-4 text-gray-300 font-medium">进度</th>
              <th class="text-left py-4 px-4 text-gray-300 font-medium">创建时间</th>
              <th class="text-left py-4 px-4 text-gray-300 font-medium">操作</th>
            </tr>
          </thead>
          <tbody>
            <tr 
              v-for="task in filteredTasks"
              :key="task.id"
              class="border-b border-gray-700/50 hover:bg-gray-800/30 transition-colors"
            >
              <td class="py-4 px-4 text-tech-blue font-mono">#{{ task.id }}</td>
              <td class="py-4 px-4 text-white">{{ task.name }}</td>
              <td class="py-4 px-4">
                <span class="flex items-center">
                  <span 
                    class="status-indicator w-2 h-2 rounded-full mr-2"
                    :class="getStatusIndicatorClass(task.status)"
                  ></span>
                  <span :class="getStatusTextClass(task.status)">
                    {{ getStatusText(task.status) }}
                  </span>
                </span>
              </td>
              <td class="py-4 px-4">
                <div class="flex items-center space-x-2">
                  <div class="w-20 h-2 bg-gray-700 rounded-full overflow-hidden">
                    <div 
                      class="tech-progress h-full transition-all duration-500"
                      :style="{ width: task.progress + '%' }"
                    ></div>
                  </div>
                  <span class="text-gray-400 text-sm">{{ task.progress }}%</span>
                </div>
              </td>
              <td class="py-4 px-4 text-gray-400">{{ task.startTime }}</td>
              <td class="py-4 px-4">
                <div class="flex space-x-2">
                  <router-link 
                    :to="`/task/details/${task.id}`"
                    class="text-tech-blue hover:text-tech-purple transition-colors"
                    title="查看详情"
                  >
                    <i class="fas fa-eye"></i>
                  </router-link>
                  <button 
                    v-if="task.status === 'running'"
                    @click="pauseTask(task.id)"
                    class="text-yellow-400 hover:text-yellow-300 transition-colors"
                    title="暂停任务"
                  >
                    <i class="fas fa-pause"></i>
                  </button>
                  <button 
                    v-if="task.status === 'running'"
                    @click="stopTask(task.id)"
                    class="text-red-400 hover:text-red-300 transition-colors"
                    title="停止任务"
                  >
                    <i class="fas fa-stop"></i>
                  </button>
                  <button 
                    v-if="task.status === 'completed'"
                    @click="downloadReport(task.id)"
                    class="text-green-400 hover:text-green-300 transition-colors"
                    title="下载报告"
                  >
                    <i class="fas fa-download"></i>
                  </button>
                  <button 
                    @click="duplicateTask(task.id)"
                    class="text-gray-400 hover:text-gray-300 transition-colors"
                    title="复制任务"
                  >
                    <i class="fas fa-copy"></i>
                  </button>
                </div>
              </td>
            </tr>
          </tbody>
        </table>
      </div>
      
      <!-- 分页 -->
      <div class="flex justify-between items-center mt-6">
        <div class="text-gray-400 text-sm">
          显示 {{ (currentPage - 1) * pageSize + 1 }} 到 {{ Math.min(currentPage * pageSize, totalTasks) }} 条，共 {{ totalTasks }} 条
        </div>
        <div class="flex space-x-2">
          <button 
            :disabled="currentPage === 1"
            @click="currentPage--"
            class="px-3 py-1 border border-gray-600 rounded text-gray-300 disabled:opacity-50 hover:bg-gray-700"
          >
            上一页
          </button>
          <button 
            :disabled="currentPage === totalPages"
            @click="currentPage++"
            class="px-3 py-1 border border-gray-600 rounded text-gray-300 disabled:opacity-50 hover:bg-gray-700"
          >
            下一页
          </button>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed } from 'vue'
import { useTaskStore } from '@/stores/task'

const taskStore = useTaskStore()
const searchQuery = ref('')
const statusFilter = ref('')
const currentPage = ref(1)
const pageSize = ref(10)

const filteredTasks = computed(() => {
  let filtered = taskStore.tasks
  
  if (searchQuery.value) {
    filtered = filtered.filter(task => 
      task.name.toLowerCase().includes(searchQuery.value.toLowerCase())
    )
  }
  
  if (statusFilter.value) {
    filtered = filtered.filter(task => task.status === statusFilter.value)
  }
  
  return filtered
})

const totalTasks = computed(() => filteredTasks.value.length)
const totalPages = computed(() => Math.ceil(totalTasks.value / pageSize.value))

const getStatusIndicatorClass = (status: string) => {
  switch (status) {
    case 'running':
      return 'status-indicator busy bg-yellow-400'
    case 'completed':
      return 'status-indicator online bg-green-400'
    case 'failed':
      return 'status-indicator offline bg-red-400'
    default:
      return 'bg-gray-400'
  }
}

const getStatusTextClass = (status: string) => {
  switch (status) {
    case 'running':
      return 'text-yellow-400'
    case 'completed':
      return 'text-green-400'
    case 'failed':
      return 'text-red-400'
    default:
      return 'text-gray-400'
  }
}

const getStatusText = (status: string) => {
  switch (status) {
    case 'running':
      return '运行中'
    case 'completed':
      return '已完成'
    case 'failed':
      return '失败'
    case 'pending':
      return '等待中'
    default:
      return '未知'
  }
}

const pauseTask = (taskId: string) => {
  console.log('暂停任务:', taskId)
  // 实现暂停逻辑
}

const stopTask = (taskId: string) => {
  if (confirm('确定要停止这个任务吗？')) {
    console.log('停止任务:', taskId)
    taskStore.updateTask(taskId, { status: 'failed' })
  }
}

const downloadReport = (taskId: string) => {
  console.log('下载报告:', taskId)
  // 实现下载逻辑
}

const duplicateTask = (taskId: string) => {
  const task = taskStore.getTaskById(taskId)
  if (task) {
    taskStore.addTask({
      name: `${task.name} (副本)`,
      status: 'pending',
      progress: 0,
      device: task.device,
      type: task.type
    })
  }
}
</script>

